# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-12-7 15:11
# @file : views.py
import time
from flask import request, jsonify, make_response
from exts.auth import login_required
from exts.xjson import json_success, json_error
from settings import UPLOAD_URL
from . import goods_bp
from apps.goods.models import Goods, Goods_type
from exts import session
from sqlalchemy import or_


@goods_bp.route('/add_goods', methods=['GET', 'POST'])
@login_required
def create_goods():
    if request.method == 'POST':
        name = request.form['name']
        price = request.form['price']
        component = request.form['component']
        place_of_production = request.form['place_of_production']
        goodsType_id = request.form['goodsType_id']
        goods = Goods(name=name, price=price,
                      component=component,
                      place_of_production=place_of_production,
                      goodsType_id=goodsType_id)
        session.add(goods)
        session.commit()
        data = json_success(message='商品添加成功', data={
            'name': name,
            'component': component,
            'place_of_production': place_of_production,
            'goodsType_id': goodsType_id
        })
        response = make_response(data)
        return response


@goods_bp.route('add_goods_type', methods=['GET', 'POST'])
@login_required
def add_goods_type():
    if request.method == 'POST':
        type = request.form['type']
        if session.query(Goods_type).filter(Goods_type.type.contains(type)).all():
            data = jsonify({'code': '200', 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                            'message': '商品类型已存在，请重新添加',
                            'errorCode': ''})
            response = make_response(data)
            return response
        else:
            goods_type = Goods_type(type=type)
            session.add(goods_type)
            session.commit()
            data = json_success(message='商品类型添加成功', data={'type': type})
            response = make_response(data)
            return response


@goods_bp.route('query_goods', methods=['GET', 'POST'])
@login_required
def query_goods():
    if request.method == 'GET':
        keyword = request.args.get('search')
        goods_list = session.query(Goods). \
            filter(or_(Goods.name.contains(keyword), Goods.price.contains(keyword),
                       Goods.component.contains(keyword), Goods.place_of_production.contains(keyword),
                       Goods.date_of_manufacture.contains(keyword)))
        for goods in goods_list:
            if keyword:
                res = {
                    'id': goods.id, 'name': goods.name,
                    'component': goods.component,
                    'place_of_production': goods.place_of_production,
                    'date_of_manufacture': goods.date_of_manufacture
                }
                data = json_success(message='搜索成功', data={'data': res})
                response = make_response(data)
                return response
            if not keyword:
                data = json_error(message='输入不存在，请重新输入', data={})
                response = make_response(data)
                return response


@goods_bp.route('mod_goods', methods=['GET', 'POST'])
@login_required
def mod_goods():
    if request.method == 'GET':
        id = request.args.get('id')
        goods = Goods.query.get(id)
        return jsonify({'goods': goods})
    if request.method == 'POST':
        id = request.form.get('id')
        name = request.form.get('name')
        price = request.form.get('price')
        component = request.form.get('component')
        place_of_production = request.form.get('place_of_production')
        date_of_manufacture = request.form.get('date_of_manufacture')
        goods = session.query(Goods).filter(Goods.id == id).first()
        goods.name = name
        goods.price = price
        goods.component = component
        goods.place_of_production = place_of_production
        goods.date_of_manufacture = date_of_manufacture
        session.commit()
        return json_success(message='商品修改成功', data={
            'name': name,
            'price': price,
            'component': component,
            'place_of_production': place_of_production,
            'date_of_manufacture': date_of_manufacture
        })


@goods_bp.route('del_goods', methods=['GET', 'POST'])
@login_required
def del_goods():
    if request.method == 'POST':
        id = request.form.get('id')
        # one_or_none 只会获取一条记录，找不到记录或者多条记录时会报错
        # goods = session.query(Goods).filter(Goods.id == id).one_or_none()
        # scalar()：同one, 没有结果时返回None
        goods = session.query(Goods).filter(Goods.id == id).scalar()
        # 只获取唯一一条记录, 找不到记录或找到多条记录时会报错
        # goods = session.query(Goods).filter(Goods.id == id).one()
        if not goods:
            return json_success(message='商品不存在', data={})
        else:
            session.delete(goods)
            session.commit()
            return json_success(message='商品删除成功', data=goods.name)


